from ttzScrapyProject.constants import UrlConstant
from ttzScrapyProject.convert import parseUserItem
from ttzScrapyProject.utils import HttpUtils
from ttzScrapyProject.vo.LoginUserVo import UserVo
from ttzScrapyProject.dao.BaseDao import MysqlDao


class UserDao(MysqlDao):
    def __init__(self):
        super().__init__()
        self.cursor = self.getCursor()
        self.db = self.getDB()

    """
        调用外部接口获取用户信息
    """
    def getUserInfo(self,loginUserVo):
        try:
            userInfoUrl = f"{UrlConstant.USER_INFO_URL}{loginUserVo.usertoken}"
            userInfo = HttpUtils.get("获取用户信息", userInfoUrl)
            userInfoData = userInfo['Data']
            loginUserVo.setCoinBean(userInfoData["CoinBean"])
            loginUserVo.setUserId(userInfoData["UserId"])
            loginUserVo.setNickname(userInfoData["Nickname"])
            # 更新数据库
            self.updateUserDB(loginUserVo)
        except:
            print("获取用户信息失败")
        return loginUserVo
    """
        更新用户信息
    """
    def updateUserDB(self,loginUserVo):
        sql = "update user set user_token = %s,USER_COBIN = %s where user_phone = %s"
        values = (loginUserVo.usertoken, loginUserVo.coinBean, loginUserVo.phone)
        self.cursor.execute(sql, values)
        self.db.commit()

    """
        更新用户每日盈利情况
    """
    def updateTodayWinAmount(self,loginUserVo):
        sql = "update user set TODAY_WIN_AMOUNT = %s where USER_PHONE = %s"
        values = (loginUserVo.TodayWin, loginUserVo.phone)
        self.cursor.execute(sql, values)
        self.db.commit()

    def getAllUser(self):
        all_phone_numbers = []
        try:
            sql = "select * from user"
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            for row in result:
                all_phone_numbers.append(row[6])
            return all_phone_numbers
        except:
            return all_phone_numbers


if __name__ == '__main__':
    userDao = UserDao()
    print(userDao.getAllUser())